package com.think.admin.oauth.config;

import com.think.admin.oauth.handle.OauthAccessDeniedHandlerImpl;
import com.think.admin.oauth.handle.OauthAuthenticationEntryPointImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.expression.OAuth2WebSecurityExpressionHandler;

/**
 * <p>
 * 资源服务配置
 * </p>
 *
 * @author xwj
 * @date 2019/4/24
 */
@Configuration
@EnableResourceServer
@RequiredArgsConstructor
public class Oauth2ResourceServer extends ResourceServerConfigurerAdapter {
    private final OauthAccessDeniedHandlerImpl oauthAccessDeniedHandler;
    private final OauthAuthenticationEntryPointImpl oauthAuthenticationEntryPoint;
    private final OAuth2WebSecurityExpressionHandler oAuth2WebSecurityExpressionHandler ;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .authorizeRequests()
                .antMatchers("/admin/home/verifyCode/{token}").permitAll()
                .antMatchers("/wechat/**").permitAll()
//                .anyRequest().authenticated()
                .antMatchers("/**/js/**","/**/css/**","/**/img/**","/**/images/**","/**/fonts/**","/**/favicon.ico").permitAll()//
                .anyRequest().authenticated()
                .anyRequest().access("@permissionService.hasPermission(request,authentication)")
                .and()
                .cors().and()
                .csrf().disable();
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources
                .authenticationEntryPoint(oauthAuthenticationEntryPoint)
                .accessDeniedHandler(oauthAccessDeniedHandler)
                .expressionHandler(oAuth2WebSecurityExpressionHandler);
    }
}
